package com.yanchangapp.ui.activity.mail;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.tencent.smtt.sdk.ValueCallback;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.CheckUtils;
import com.zxl.baselib.util.PerfectClickListener;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.util.window.KeyboardHelper;
import com.yanchangapp.R;
import com.yanchangapp.adapter.MailUserAdapter;
import com.yanchangapp.commom.AppConstant;
import com.yanchangapp.model.bean.MailAtmentBean;
import com.yanchangapp.model.bean.MailUserBean;
import com.yanchangapp.model.bean.NotifyBean;
import com.yanchangapp.model.cache.UserCache;
import com.yanchangapp.model.request.SaveDraftRequest;
import com.yanchangapp.model.request.SendTotalMailRequest;
import com.yanchangapp.model.response.MailDetailResponse;
import com.yanchangapp.ui.presenter.TnspondAtPresenter;
import com.yanchangapp.ui.view.TnspondAtView;
import com.yanchangapp.util.WebviewHelper;
import com.zxl.baselib.widget.TipDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;

/**
 * 从草稿箱页以及转发,抄送一人以及抄送多人页面....
 *
 */
public class TranspondActivity extends BaseActivity<TnspondAtView, TnspondAtPresenter> implements TnspondAtView {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.ivSend)
    ImageView ivSend;
    @BindView(R.id.rvReceivers)
    RecyclerView rvReceivers;
    @BindView(R.id.etReceiver)
    EditText etReceiver;
    @BindView(R.id.ivAddReceiver)
    ImageView ivAddReceiver;
    @BindView(R.id.rvCopies)
    RecyclerView rvCopies;
    @BindView(R.id.etCopy)
    EditText etCopy;
    @BindView(R.id.ivAddCopy)
    ImageView ivAddCopy;
    @BindView(R.id.etTheme)
    EditText etTheme;
    @BindView(R.id.webView)
    WebView mWebView;
    @BindView(R.id.rvAttachmentLists)
    RecyclerView mRvAttachmentList;
    @BindView(R.id.llBody)
    LinearLayout mLlBody;
    private static final String TITLE = "title";
    private static final String MAIL_ID = "mail_id";
    private static final String RECEIVER = "receiver";
    private static final String COPY = "copy";
    private static final String THEME = "theme";
    private static final String CONTENT = "content";
    private static final String ATTACHMENT = "attachment";
    private static final String IS_FROM_SEARCH = "is_from_search";
    public static final String TITLE_DRAFT = "写信";
    public static final String TITLE_TRANS_ONE = "回复邮件";
    public static final String TITLE_TRANS_ALL = "回复邮件";
    // 进行转发...
    public static final String TITLE_ZHUAN_FA = "转发";
    // 转发
    public static final String TITLE_RETURN_BACK = "";
    private MailUserAdapter mMailReceiversAdapter;
    private MailUserAdapter mMailCopiersAdapter;
    private List<MailUserBean> mMailReceiverList;
    private List<MailUserBean> mMailCopierList;
    private List<MailAtmentBean> attachmentsList;
    private TipDialog mEnsureThemeDialog,mQuitDialog;
    private String mCurrentTheme;
    private String mWebContent;
    private BaseQuickAdapter<MailAtmentBean,BaseViewHolder> mAttachmentAdapter;
    private boolean isFirstIn = true;
    private int mMailID;
    private String title;
    private String theme;
    private String content;
    private boolean isFromSearch = false;
    private static final String TAG = "TranspondActivity";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK){
            List<MailUserBean> userBeans = (List<MailUserBean>) data.getExtras().getSerializable(ContactSelectActivity.DATA_BACK);
            // 去除空
            if (userBeans == null){
                userBeans = new ArrayList<>();
            }
            switch (requestCode){
                case ContactSelectActivity.RCODE_RECEIVER:
                    if (userBeans.size() != 0){
                        doFilter(mMailReceiverList,userBeans);
                        setSendIsEnable();
                        mMailReceiversAdapter.notifyDataSetChanged();
                    }
                    break;
                case ContactSelectActivity.RCODE_COPY:
                    if (userBeans.size() != 0){
                        doFilter(mMailCopierList,userBeans);
                        mMailCopiersAdapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }

    /**
     * 设置发送按钮是否可见...
     */
    private void setSendIsEnable(){
        if (mMailReceiverList.size() > 0){
            ivSend.setEnabled(true);
        }else {
            ivSend.setEnabled(false);
        }
    }

    public static void jumpFromDetail(Activity activity,
                                      String title,
                                      List<MailUserBean> mReceivers,
                                      List<MailUserBean> mCopes,
                                      String theme,
                                      String content,
                                      List<MailAtmentBean> attachments,
                                      boolean isFromSearch){
        Intent intent = new Intent(activity,TranspondActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(TITLE,title);
        bundle.putSerializable(RECEIVER,(Serializable)mReceivers);
        bundle.putSerializable(COPY,(Serializable)mCopes);
        bundle.putSerializable(ATTACHMENT,(Serializable)attachments);
        bundle.putString(THEME,theme);
        bundle.putString(CONTENT,content);
        bundle.putBoolean(IS_FROM_SEARCH,isFromSearch);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    // 从草稿箱进入转发页面...
    public static void showFromDraft(Activity context,int mailID) {
        Intent intent = new Intent(context, TranspondActivity.class);
        intent.putExtra(MAIL_ID,mailID);
        intent.putExtra(TITLE,TITLE_DRAFT);
        context.startActivity(intent);
    }

    public static void showFromDraft(Activity context,int mailID,boolean isFromSearch) {
        Intent intent = new Intent(context, TranspondActivity.class);
        intent.putExtra(MAIL_ID,mailID);
        intent.putExtra(TITLE,TITLE_DRAFT);
        intent.putExtra(IS_FROM_SEARCH,isFromSearch);
        context.startActivity(intent);
    }


    @Override
    protected void init() {
        // 初始化ArrayList
        mMailID = 0;
        mMailReceiverList = new ArrayList<>();
        mMailCopierList = new ArrayList<>();
        attachmentsList = new ArrayList<>();
        if (getIntent() != null){
            // 获得标题
            title = getIntent().getStringExtra(TITLE);
            if (TITLE_DRAFT.equals(title)){
               mMailID = getIntent().getIntExtra(MAIL_ID,0);
            }else {
               theme = getIntent().getStringExtra(THEME);
               content = getIntent().getStringExtra(CONTENT);
               mMailReceiverList = (List<MailUserBean>)getIntent().getExtras().getSerializable(RECEIVER);
               mMailCopierList = (List<MailUserBean>)getIntent().getExtras().getSerializable(COPY);
               attachmentsList = (List<MailAtmentBean>)getIntent().getExtras().getSerializable(ATTACHMENT);
            }
            if (getIntent().hasExtra(IS_FROM_SEARCH)){
                isFromSearch = getIntent().getBooleanExtra(IS_FROM_SEARCH,false);
            }
        }
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_transpond;
    }

    @Override
    protected TnspondAtPresenter createPresenter() {
        return new TnspondAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setSendIsEnable();
        // 设置标题
        tvToolbarTitle.setText(title);
        //initWebView();
        initWebView(mWebView);
        initAdapter();
        // 是否需要进行网络请求...
        if (mMailID != 0){
            // 从草稿箱进入邮件...
            mPresenter.queryMailDetailInfo(mMailID);
        }else {
            // 直接呈现即可...
            // 进行内容的呈现...
            if (theme != null){
                etTheme.setText(theme);
            }

            if (content != null){
                fillWebviewBody(mWebView,content);
            }
        }
    }

    private void initAdapter() {
        LinearLayoutManager receiverManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        LinearLayoutManager copyManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        receiverManager.setSmoothScrollbarEnabled(true);
        receiverManager.setAutoMeasureEnabled(true);
        rvReceivers.setHasFixedSize(true);
        rvReceivers.setNestedScrollingEnabled(false);
        copyManager.setSmoothScrollbarEnabled(true);
        copyManager.setAutoMeasureEnabled(true);
        rvCopies.setHasFixedSize(true);
        rvCopies.setNestedScrollingEnabled(false);
        rvReceivers.setLayoutManager(receiverManager);
        rvCopies.setLayoutManager(copyManager);
        mMailReceiversAdapter = new MailUserAdapter(R.layout.item_user_delete,mMailReceiverList);
        mMailCopiersAdapter = new MailUserAdapter(R.layout.item_user_delete,mMailCopierList);
        rvReceivers.setAdapter(mMailReceiversAdapter);
        rvCopies.setAdapter(mMailCopiersAdapter);
        mMailCopiersAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.ivDelete){
                mMailCopierList.remove(position);
                mMailCopiersAdapter.notifyDataSetChanged();
            }
        });

        mMailReceiversAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.ivDelete){
                mMailReceiverList.remove(position);
                setSendIsEnable();
                mMailReceiversAdapter.notifyDataSetChanged();
            }
        });


        LinearLayoutManager attachmentManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        attachmentManager.setSmoothScrollbarEnabled(true);
        attachmentManager.setAutoMeasureEnabled(true);
        mRvAttachmentList.setLayoutManager(attachmentManager);
        mAttachmentAdapter = new BaseQuickAdapter<MailAtmentBean, BaseViewHolder>(R.layout.item_attachment_show,attachmentsList) {
            @Override
            protected void convert(BaseViewHolder helper, MailAtmentBean item) {
                // 设置附件名
                helper.setText(R.id.tvAttachment,item.getName());
                helper.addOnClickListener(R.id.tvLook);
            }
        };
        mAttachmentAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            // 点击附件 进行查看工作...
            if (view.getId() == R.id.tvLook){
                AttachmentShowActivity.show(TranspondActivity.this,attachmentsList.get(position).getPath());
            }
        });
        mRvAttachmentList.setAdapter(mAttachmentAdapter);
    }

    // 这么看来x5浏览器还是有其必要性的
    private void initWebView() {
        mWebView.getSettings();
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setHorizontalScrollbarOverlay(false);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setVerticalScrollbarOverlay(false);
    }

    // 初始化webview
    @SuppressLint("AddJavascriptInterface")
    private void initWebView(WebView webView){
        // 隐藏滑动
        webView.setHorizontalScrollBarEnabled(false);
        webView.setVerticalScrollBarEnabled(false);
        WebviewHelper.initWebView(webView);
        webView.addJavascriptInterface(new JSInterface(),"latte");
        webView.setOnTouchListener(new View.OnTouchListener() {
            private float startx;
            private float starty;
            private float offsetx;
            private float offsety;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        v.getParent().requestDisallowInterceptTouchEvent(true);
                        startx = event.getX();
                        starty = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        offsetx = Math.abs(event.getX() - startx);
                        offsety = Math.abs(event.getY() - starty);
                        if (offsetx > offsety) {
                            v.getParent().requestDisallowInterceptTouchEvent(true);
                        } else {
                            v.getParent().requestDisallowInterceptTouchEvent(false);
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void showThemeDialog() {
        if (mEnsureThemeDialog == null){
            mEnsureThemeDialog = new TipDialog.Builder(this)
                    .setMessage("确定发送无主题邮件?")
                    .setEnsureClickListener(new TipDialog.EnsureClickListener() {
                        @Override
                        public void onEnsureClick(TipDialog tipDialog) {
                            tipDialog.dismiss();
                            // 执行确认主题逻辑
                            mCurrentTheme = "来自"+ UserCache.getName() +"的邮件";
                            queryWriteData();
                        }
                    }).build();
        }
        mEnsureThemeDialog.show();
    }

    /**
     * 确认退出弹框...
     */
    private void showQuitDialog() {
        if (mQuitDialog == null){
            mQuitDialog = new TipDialog.Builder(this)
                    .setMessage("是否保存为草稿？")
                    .setEnsureText("保存")
                    .setCancelText("不保存")
                    .setCancelCickListener(new TipDialog.CancelClickListener() {
                        @Override
                        public void onCancelClick(TipDialog tipDialog) {
                            tipDialog.dismiss();
                            finish();
                        }
                    })
                    .setEnsureClickListener(new TipDialog.EnsureClickListener() {
                        @Override
                        public void onEnsureClick(TipDialog tipDialog) {
                            tipDialog.dismiss();
                            httpSaveDraft();
                        }
                    }).build();
        }
        mQuitDialog.show();
    }

    // 进行保存工作...
    private void httpSaveDraft() {
        // todo 进行保存...
        SaveDraftRequest saveDraftRequest = new SaveDraftRequest
                (mMailID,mMailReceiverList,mMailCopierList,etTheme.getText().toString(),mWebContent);
        mPresenter.saveDraftMail(saveDraftRequest);
    }

    private final class JSInterface{
        @SuppressLint("JavascriptInterface")
        @JavascriptInterface
        public void event(final String info){
            // 获得传递的值
            Gson gson = new Gson();
            NotifyBean notifyBean = gson.fromJson(info, NotifyBean.class);
            String command =  notifyBean.command;
            if ("write".equals(command)){
                if (mMailID == 0){
                    mPresenter.sendMail(new SendTotalMailRequest(mMailReceiverList,
                            mMailCopierList,
                            mCurrentTheme,
                            notifyBean.msg,
                            attachmentsList));
                }else {
                    mPresenter.sendMail(new SendTotalMailRequest(mMailReceiverList,
                            mMailCopierList,
                            mCurrentTheme,
                            notifyBean.msg,
                            attachmentsList,
                            mMailID));
                }
            }else if ("back".equals(command)){
                mWebContent = notifyBean.msg;
                showQuitDialog();
            }
        }
    }

    // 查询写信数据
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void queryWriteData(){
        mWebView.evaluateJavascript("javascript:queryWriteData();",
                new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {

                    }
                });
    }

    // 查询返回数据
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void queryIsNullData(){
        mWebView.evaluateJavascript("javascript:queryBackData();",
                new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {

                    }
                });
    }

    // 等等这里有点问题的

    @Override
    protected void initData() {
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void initListener() {
        mLlBody.setOnClickListener(v -> {
            if (getCurrentFocus() != null) {
                if (etReceiver.hasFocus()){
                    etReceiver.clearFocus();
                }

                if (etCopy.hasFocus()){
                    etCopy.clearFocus();
                }

                if (etTheme.hasFocus()){
                    etTheme.clearFocus();
                }
                KeyboardHelper.hideKeyboard(mLlBody, getCurrentFocus().getWindowToken());
            }
        });

        // 返回按钮点击事件
        ivToolbarNavigation.setOnClickListener(new PerfectClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            protected void onNoDoubleClick(View v) {
                queryIsNullData();
            }
        });


        // 输入框点击事件....
        etReceiver.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus){
                etReceiverIn();
            }
        });

        etCopy.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus){
                etCopyIn();
            }
        });


        // 监听输入框的回车事件...
        etTheme.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER){
                if (event.getAction() == KeyEvent.ACTION_DOWN){
                    // todo 内容变化
                    etTheme.clearFocus();
                    if (getCurrentFocus() != null) {
                        KeyboardHelper.hideKeyboard(mLlBody, getCurrentFocus().getWindowToken());
                    }
                }
                return  true;
            }
            return false;
        });

        etReceiver.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER){
                if (event.getAction() == KeyEvent.ACTION_DOWN){
                    // todo 内容变化
                    etReceiverIn();
                }
                return  true;
            }
            return false;
        });

        etCopy.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER){
                if (event.getAction() == KeyEvent.ACTION_DOWN){
                    // todo 内容变化
                    etCopyIn();
                }
                return  true;
            }
            return false;
        });

        // 发送点击事件...
        ivSend.setOnClickListener(v -> {
            String theme = etTheme.getText().toString();
            if (TextUtils.isEmpty(theme)){
                showThemeDialog();
                return;
            }
            mCurrentTheme = theme;
            queryWriteData();
        });

        // 接收点击事件
        ivAddReceiver.setOnClickListener(v -> ContactSelectActivity.show(TranspondActivity.this,ContactSelectActivity.RCODE_RECEIVER));

        // 抄送点击事件
        ivAddCopy.setOnClickListener(v -> ContactSelectActivity.show(TranspondActivity.this,ContactSelectActivity.RCODE_COPY));
    }

    // 发送人
    private void etReceiverIn(){
        String receiver = etReceiver.getText().toString();
        if (CheckUtils.isEmail(receiver)){
            String[] rvArray = receiver.split("@");
            MailUserBean mailUserBean = new MailUserBean(receiver, rvArray[0], rvArray[0]);
            doFilter(mMailReceiverList,mailUserBean);
            mMailReceiversAdapter.notifyDataSetChanged();
        }
        setSendIsEnable();
        etReceiver.setText("");
    }

    // 抄送人
    private void etCopyIn(){
        String copy = etCopy.getText().toString();
        if (CheckUtils.isEmail(copy)){
            String[] rvArray = copy.split("@");
            MailUserBean mailUserBean = new MailUserBean(copy, rvArray[0], rvArray[0]);
            doFilter(mMailCopierList,mailUserBean);
            mMailCopiersAdapter.notifyDataSetChanged();
        }
        etCopy.setText("");
    }

    /**
     * 进行合并筛选
     * @param target
     * @param two
     */
    private void doFilter(List<MailUserBean> target,List<MailUserBean> two){
        if (target.size() == 0){
            target.addAll(two);
            return;
        }
        List<MailUserBean> three = new ArrayList<>();
        for (int i=0;i<two.size();i++){
            MailUserBean targetBean =  two.get(i);
            for (int j=0;j<target.size();j++){
                MailUserBean nextBean = target.get(j);
                if (targetBean.getAddress().equals(nextBean.getAddress())){
                    target.set(j,targetBean);
                    break;
                }
                if (j == (target.size()-1)){
                    three.add(targetBean);
                }
            }
        }
        target.addAll(three);
    }

    private void doFilter(List<MailUserBean> target,MailUserBean bean){
        if (target.size() == 0){
            target.add(bean);
        }
        for (int i=0;i<target.size();i++){
            MailUserBean userBean = target.get(i);
            if (bean.getAddress().equals(userBean.getAddress())){
                target.set(i,bean);
                break;
            }
            if (i == (target.size()-1)){
                target.add(bean);
            }
        }
    }

    /**
     * webview编辑展示
     * @param webview
     * @param content
     */
    private void fillWebviewBody(WebView webview,String content){
        StringBuffer body = new StringBuffer();
        body.append(WebviewHelper.getTransWVStartString());
        body.append(content);
        body.append(WebviewHelper.getTransWVEndString());
        webview.loadDataWithBaseURL((String)null, body.toString(), "text/html",
                "utf-8", (String)null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isFirstIn){
            isFirstIn = false;
        }else {
            mWebView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWebView.onPause();
        mWebView.getSettings().setLightTouchEnabled(false);
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null){
            mWebView.destroy();
        }
        super.onDestroy();
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            queryIsNullData();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void queryMailDetailSuccess(MailDetailResponse.DataBean dataBean) {
        theme = dataBean.getSubject();
        if (theme != null){
            etTheme.setText(theme);
        }
        // 设置列表
        mMailReceiverList.clear();
        if (dataBean.getToUsers() != null && dataBean.getToUsers().size() != 0){
            mMailReceiverList.addAll(dataBean.getToUsers());
            // 刷新列表
            mMailReceiversAdapter.notifyDataSetChanged();
        }
        if (mMailReceiverList.size() != 0){
            ivSend.setEnabled(true);
        }
        mMailCopierList.clear();
        if (dataBean.getCcUsers() != null && dataBean.getCcUsers().size() != 0){
            mMailCopierList.addAll(dataBean.getCcUsers());
            // 刷新列表
            mMailCopiersAdapter.notifyDataSetChanged();
        }
        content = dataBean.getContent();
        fillWebviewBody(mWebView,content);
    }

    @Override
    public void queryMailDetailFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void sendMailSuccess() {
        // 发送邮件成功
        if (mMailID != 0){
            mRxManager.post(AppConstant.NOTIFY_MAIL_SAVE_DRAFT_SUCCESS,true);
        }else {
            mRxManager.post(AppConstant.NOTIFY_MAIL_WRITE_SUCCESS,true);
        }
        UIUtils.showToast("发送成功");
        finish();
    }

    @Override
    public void sendMailFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void saveDraftSuccess() {
        mRxManager.post(AppConstant.NOTIFY_MAIL_SAVE_DRAFT_SUCCESS,true);
        finish();
    }

    @Override
    public void saveDraftFailure(String err) {
        UIUtils.showToast(err);
    }
}
